<template>
  <div>
    <el-card style="margin: 20px 0px;">
      <CategorySelect @getcategoryId="getcategoryId" :show="isShowTable"></CategorySelect>
    </el-card>
    <el-card>
      <div v-show="isShowTable">

        <el-button @click="addAttr" type="primary" icon="el-icon-plus" :disabled="!category3Id">添加属性</el-button>
        <el-table :data="attrList" style="width: 100%">
          <el-table-column prop="index" label="序号" width="80">
          </el-table-column>

          <el-table-column prop="attrName" label="属性名称" width="150">
          </el-table-column>

          <el-table-column prop="prop" label="属性值列表" width="width">
            <template slot-scope="{row,$index}">
              <el-tag type="success" v-for="(attrValue, index) in row.attrValueList" :key="attrValue.id"
                style="margin: 0px 20px;">
                {{ attrValue.valueName }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="prop" label="操作" width="150">
            <template slot-scope="{row,$index}">
              <el-button type="warning" icon="el-icon-edit" size="mini" @click="updateAttr(row)"></el-button>
              <el-button type="danger" icon="el-icon-delete" size="mini"></el-button>
            </template>
          </el-table-column>
        </el-table>

      </div>

      <div v-show="!isShowTable">
        <el-form :inline="true" label-width="80px" :model="attrInfo">
          <el-form-item label="属性名">
            <el-input placeholder="请输入属性名" v-model="attrInfo.attrName">
            </el-input>
          </el-form-item>
        </el-form>

        <el-button type="primary" icon="el-icon-plus" @click="addAttrValue"
          :disabled="!attrInfo.attrName">添加属性值</el-button>
        <el-button @click="isShowTable = true">取消</el-button>

        <el-table style="width: 100% ;margin:20px 0" border :data="attrInfo.attrValueList">
          <el-table-column type="index" label="序号" width="80" align="center">
          </el-table-column>

          <el-table-column label="属性值名称" width="width" prop="prop">
            <template slot-scope="{row,$index}">
              <el-input v-model="row.valueName" placeholder="请输入属性值名称" size="mini" v-if="row.flag" @blur="toLook(row)"
                @keyup.native.enter="toLook(row)" :ref="$index"></el-input>
              <span v-else @click="toEdit(row, $index)" style="display: block;">{{ row.valueName }}</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="width">
            <template slot-scope="{row,$index}">

              <el-popconfirm :title="`你确定删除${row.valueName}吗`" @onConfirm="deleteAttrValue($index)">
                <el-button slot="reference" type="danger" icon="el-icon-delete" size="mini">删除</el-button>
              </el-popconfirm>

            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="addOrUpdateAttr"
          :disabled="this.attrInfo.attrValueList.length < 1">保存</el-button>
        <el-button @click="isShowTable = true">取消</el-button>
      </div>


    </el-card>
  </div>
</template>

<script>
import cloneDeep from 'lodash/cloneDeep'//按需引入lodash的深拷贝
export default {
  name: "Attr",
  data() {
    return {
      category1Id: '',
      category2Id: '',
      category3Id: '',
      attrList: [],
      isShowTable: true,
      // 收集新增属性|修改属性使用的
      attrInfo: {
        attrName: "",
        attrValueList: [],
        categoryId: 0,
        categoryLevel: 3,
      },

    }
  },
  methods: {
    async getAttrList() {
      let result = await this.$API.attr.reqAttrList(this.category1Id, this.category2Id, this.category3Id)
      if (result.code == 200) {
        this.attrList = result.data
      }

    },
    getcategoryId({ categoryId, level }) {
      if (level == 1) {
        this.category1Id = categoryId
        this.category2Id = ''
        this.category3Id = ''
      } else if (level == 2) {
        this.category2Id = categoryId
        this.category3Id = ''
      } else {
        this.category3Id = categoryId
        this.getAttrList()
      }
    },
    addAttrValue() {
      this.attrInfo.attrValueList.push({ attrId: this.attrInfo.id, valueName: '', flag: true, })
      this.$nextTick(() => {
        this.$refs[this.attrInfo.attrValueList.length - 1].focus()
      })
    },
    addAttr() {
      this.isShowTable = false;

      this.attrInfo = {
        attrName: "",
        attrValueList: [],
        categoryId: this.category3Id,
        categoryLevel: 3,
      }
    },
    updateAttr(row) {
      this.isShowTable = false;
      //解决  输入修改的值，点击取消，值也被改变了 的问题
      // this.attrInfo = row;这相当于，两者指向同一个对象，一个改变另一个也跟着改变，
      this.attrInfo = cloneDeep(row)//由于数据复杂，浅拷贝无法将所有的值拷贝过去，所以用深拷贝，但他们都是拷贝，这相当于创建了一个新对象，这样两者就没有关系了  
      this.attrInfo.attrValueList.forEach(item => {
        //item.flag = false;错误写法。这样写，新增的flag不是响应式数据
        this.$set(item, 'flag', false)

      });

    },
    toLook(row) {
      if (row.valueName.trim() == '') {
        this.$message('属性值不能为空')
        return;
      }

      //属性值不能重复
      let isRepeat = this.attrInfo.attrValueList.some(item => {
        if (row !== item) {//row代表的是要添加的属性值对象，但是在点击添加属性按钮的时候，数组就把这个对象加进去了，这个判断是为了避免自己和自己比较，地址相同就是同一个对象
          return row.valueName == item.valueName
        }
      })
      if (isRepeat) {
        this.$message('已有相同的属性值')
        return;
      }
      row.flag = false
    },
    toEdit(row, index) {
      row.flag = true;
      // console.log(this.$refs);input标签有很多，对于浏览器而言，页面的重新渲染和重排是耗时间的，不可能一下就定位到当前索引的input标签
      this.$nextTick(() => {
        this.$refs[index].focus();
      })
    },
    deleteAttrValue(index) {
      this.attrInfo.attrValueList.splice(index, 1)
    },
    async addOrUpdateAttr() {
      this.attrInfo.attrValueList = this.attrInfo.attrValueList.filter((item) => {
        if (item.valueName.trim() != '') {
          delete item.flag;
          return true;//意思是保留这个item
        }
      })
      try {
        await this.$API.attr.reqAddOrUpdateAttr(this.attrInfo);
        this.isShowTable = true;
        this.$message({ type: 'success', message: '保存成功' });
        this.getAttrList();

      } catch (error) {

      }

    }

  }
}
</script>


<style scoped></style>
